<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="loadData(1)">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item
              label="渠道">
              <a-select
                v-decorator="['channelId', {}]"
                v-model="queryParam.channelId"
                show-search
                optionFilterProp="children"
                style="width: 100%"
                :getPopupContainer="node => node.parentNode"
                @change="changeMode"
                placeholder="请选择渠道">
                <a-select-option v-for="(channel,channelIdIndex) in optChannelList" :key="channel.id.toString()"
                                 :value="channel.id">
                  {{ channel.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="9" :sm="8">
            <a-form-item
              label="经销商">
              <a-select
                v-decorator="['storeId', {}]"
                v-model="queryParam.storeId"
                show-search
                optionFilterProp="children"
                style="width: 100%"
                :getPopupContainer="node => node.parentNode"
                @change="changeStore"
                placeholder="请选择经销商">
                <a-select-option v-for="(store,storeIndex) in optStoreList" :key="store.value.toString()"
                                 :value="store.value">
                  {{ store.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="loadData(1)" icon="search">查询</a-button>
              <a-button @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>

            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="add" type="primary" icon="plus">新增</a-button>
      <a-button @click="save" type="primary" >保存</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
<!--          <a @click="handleEdit(record)">编辑</a>-->
          <!--                <a-popconfirm title="确定删除吗?" @confirm="() => deleteLine(record.id)">-->
                  <a @click="deleteLine(record.id,record)">删除</a>
          <!--                </a-popconfirm>-->
        </span>
        <div slot="box" slot-scope="box, row">
          <a-input-number
            id="inputNumber4"
            style="width: 150px;"
            :precision="0"
            :value="box"
            :min="-1"
            @change="onChangeBox($event, row)"
          />
        </div>
        <div slot="price" slot-scope="price, row">
          <a-input-number
            id="inputNumber3"
            style="width: 150px;"
            :precision="0"
            :value="price"
            :min="-1"
            @change="onChangePrice($event, row)"
          />
        </div>
        <div slot="minimumDistance" slot-scope="minimumDistance, row">
          <a-input-number
            id="inputNumber1"
            style="width: 150px;"
            :precision="0"
            :value="minimumDistance"
            :min="0"
            @change="onChangeMinimumDistance($event, row)"
          />
        </div>
        <div slot="maximumDistance" slot-scope="maximumDistance, row">
          <a-input-number
            id="inputNumber2"
            style="width: 150px;"
            :precision="0"
            :value="maximumDistance"
            :min="0"
            @change="onChangeMaximumDistance($event, row)"
          />
        </div>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <omsOrderPriceDistance-modal ref="modalForm" @ok="modalFormOk"></omsOrderPriceDistance-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import OmsOrderPriceDistanceModal from './modules/OmsOrderPriceDistanceModal'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, httpAction, postAction} from "@api/manage";
import JMultiSelectTag from '../../components/dict/JMultiSelectTag'

export default {
  name: "OmsOrderPriceDistanceList",
  mixins: [JeecgListMixin],
  components: {
    OmsOrderPriceDistanceModal,
    JMultiSelectTag,
  },
  data() {
    return {
      description: '订单起订金额设置管理页面',
      dataSource: [],
      channelId: "",
      optChannelList: [],
      optStoreList: [],
      storeId: "",
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '（大于等于）距离km',
          align: "center",
          dataIndex: 'minimumDistance',
          scopedSlots: {customRender: "minimumDistance"}
        },
        {
          title: '(小于)距离km',
          align: "center",
          dataIndex: 'maximumDistance',
          scopedSlots: {customRender: "maximumDistance"}
        },
        {
          title: '订单起订金额(元,-1代表不限制)',
          align: "center",
          dataIndex: 'price',
          scopedSlots: {customRender: "price"}
        },
        {
          title: '起订数量(箱,-1代表不限制)',
          align: "center",
          dataIndex: 'box',
          scopedSlots: {customRender: "box"}
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/oms/omsOrderPriceDistance/list",
        delete: "/oms/omsOrderPriceDistance/delete",
        deleteBatch: "/oms/omsOrderPriceDistance/deleteBatch",
        add: "/oms/omsOrderPriceDistance/add",
        addBatch: "/oms/omsOrderPriceDistance/addBatch",
        channelListUrl: 'stm/stmChannelInfo/channelListAndOrderDistance',
        storeListUrl: 'stm/stmStoreInfo/storeListAndOrderDistance',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.getChannelList();
    this.getStoreList();
  },
  methods: {

    add() {
      console.log(1111)
      let itemCount = this.dataSource.length + 1;
      let priceLine = {
        minimumDistance: "0",
        maximumDistance: "9999",
        price: "-1",
        tempId: itemCount,
        channelId: this.channelId,
        box: '-1',
        storeId:this.storeId
      };
      this.dataSource.push(priceLine);
    },
    onChangePrice(event, row) {
      if (event === "" || event == null) {
        return;
      }
      if (event === -1 && row.box === -1) {
        row.price="";
        return;
      }
      row.price = event;
    },
    onChangeBox(event, row) {
      console.log(33333)
      if (event === "" || event == null) {
        return;
      }
      if (event === -1 && row.price === -1) {
        row.box ="";
        return;
      }
      row.box = event;
    },
    onChangeMaximumDistance(event, row) {
      if (event === "" || event == null) {
        return;
      }
      row.maximumDistance = event;
    },
    onChangeMinimumDistance(event, row) {
      if (event === "" || event == null) {
        return;
      }
      row.minimumDistance = event;
    },

    deleteLine(id, record) {
      let that = this;
      if (id > 0) {
        this.$confirm({
          title: '确认删除该记录？',
          onOk: function () {
            if (!that.url.delete) {
              that.$message.error("请设置url.delete属性!")
              return
            }

            deleteAction(that.url.delete, {id: id}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        })
      } else {
        let index = this.dataSource.findIndex(item => {
          if (item.tempId == record.tempId) {
            return true
          }
        })
        this.dataSource.splice(index, 1);
      }
    },
    save() {
      if (this.channelId == "" && this.storeId==="") {
        this.$message.warning("请选择渠道或经销商!");
        return;
      }
      if (this.channelId != "" && this.storeId!="") {
        this.$message.warning("不能同时选择渠道和经销商进行设置!");
        return;
      }
      let param = this.dataSource;
      this.dataSource.sort(function (a, b) {
        return a.minimumDistance - b.minimumDistance;
      })
      for (let i = 0; i < param.length - 1; i++) {
        let currentPriceObj = param[i];
        let nextPriceObj = param[i + 1]
        if (currentPriceObj.maximumDistance.length == 0 || currentPriceObj.minimumDistance.length == 0
          || currentPriceObj.price.length == 0 || currentPriceObj.box.length == 0) {
          this.$message.warning("有输入框未填值，请填完后再提交");
          return;
        }
        if (currentPriceObj.maximumDistance != nextPriceObj.minimumDistance) {
          this.$message.warning("输入的距离第" + (i + 1) + "行与" + (i + 2) + "行距离不连续，请重新输入。");
          return;
        }
        if (currentPriceObj.price > nextPriceObj.price) {
          this.$message.warning("输入的价格第" + (i + 1) + "行大于" + (i + 2) + "行的价格，请重新输入。");
          return;
        }
        if (currentPriceObj.box > nextPriceObj.box) {
          this.$message.warning("输入的箱数第" + (i + 1) + "行大于" + (i + 2) + "行的值，请重新输入。");
          return;
        }
        if (i == param.length - 2) {
          break;
        }
      }


      postAction(this.url.addBatch, param).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
          this.loadData();
        } else {
          this.$message.warning(res.message);
        }
      }).finally(() => {
        that.close();
      })
    },
    changeMode(val) {
      this.channelId = val;
      this.loadData(1);
    },
    getChannelList() {
      let param = {};
      getAction(this.url.channelListUrl, param).then(res => {
        if (res.success) {
          this.optChannelList = res.result;
          this.optChannelList.push({id: "", name: "请选择渠道"})
          this.optChannelList.reverse();
        } else {
          console.log(res.message)
        }
      })
    },
    getStoreList() {
      let param = {};
      getAction(this.url.storeListUrl, param).then(res => {
        if (res.success) {
          this.optStoreList = res.result;
          this.optStoreList.push({value: "", label: "请选择经销商"})
          this.optStoreList.reverse();
        } else {
          console.log(res.message)
        }
      })
    },
    changeStore: function (value) {
      this.storeId = value;
      this.loadData(1);
    },
    loadData(arg) {
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      params.storeId=this.storeId;
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          this.ipagination.total = res.result.total;
        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>